package pong;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import pong.Communication;

class Consts
{
    public static final int port = 12348;
}
public class Server
{
   private ObjectOutputStream output; // output stream to client
   private ObjectInputStream input; // input stream from client
   private ServerSocket server; // server socket
   private Socket connection; // connection to client
   //private int counter = 1; // counter of number of connections
   private Communication communicay;
   Timer t;

   // set up GUI
   public Server()
   {
            //enterField.addActionListener(
         ActionListener al =new ActionListener() 
         {
            // send message to client
            @Override
            public void actionPerformed( ActionEvent event )
            {
               sendData( new Communication(new Point(7, 7), Sender.Ball) );
                System.out.println("sendData actionPerformed server");
//               enterField.setText( "" );
            } // end method actionPerformed

         }; // end anonymous inner class
         t = new Timer(100, al);
      //); // end call to addActionListener;
   } // end Server constructor


   // set up and run server 
   public void runServer()
   {
      try // set up server to receive connections; process connections
      {
         server = new ServerSocket(Consts.port, 100 ); // create ServerSocket

         while ( true ) 
         {
            try 
            {
               waitForConnection(); // wait for a connection
               getStreams(); // get input & output streams
               processConnection(); // process connection
            } // end try
            catch ( EOFException eofException ) 
            {
               eofException.printStackTrace();
            } // end catch
            finally 
            {
               closeConnection(); //  close connection
               //++counter;
            } // end finally
         } // end while
      } // end try
      catch ( IOException ioException ) 
      {
         ioException.printStackTrace();
      } // end catch
   } // end method runServer

   // wait for connection to arrive, then display connection info
   private void waitForConnection() throws IOException
   {
      displayMessage( "Waiting for connection\n" );
      connection = server.accept(); // allow server to accept connection
         t.start();
      displayMessage( "Connection " + communicay + " received from: " +
         connection.getInetAddress().getHostName() );
   } // end method waitForConnection

   // get streams to send and receive data
   private void getStreams() throws IOException
   {
      // set up output stream for objects
      output = new ObjectOutputStream( connection.getOutputStream() );
      output.flush(); // flush output buffer to send header information

      // set up input stream for objects
      input = new ObjectInputStream( connection.getInputStream() );

      displayMessage( "\nGot I/O streams\n" );
   } // end method getStreams

   // process connection with client
   private void processConnection() throws IOException
   {

       Communication comm = null;
      sendData( new Communication(new Point(7,8), Sender.Ball)); // send connection successful message

      // enable enterField so server user can send messages
      //setTextFieldEditable( true );

      do // process messages sent from client
      { 
         try // read message and display it
         {
            comm = ( Communication ) input.readObject(); // read new message
            displayMessage( "\n IN CLIENT: " + comm ); // display message
         } // end try
         catch ( ClassNotFoundException classNotFoundException ) 
         {
            displayMessage( "\nUnknown object type received" );
         } // end catch

      } while ( comm.location.x != -1 );
   } // end method processConnection

   // close streams and socket
   private void closeConnection() 
   {
      displayMessage( "\nTerminating connection\n" );
      //setTextFieldEditable( false ); // disable enterField

      try 
      {
         output.close(); // close output stream
         input.close(); // close input stream
         connection.close(); // close socket
      } // end try
      catch ( IOException ioException ) 
      {
         ioException.printStackTrace();
      } // end catch
   } // end method closeConnection

   // send message to client
   private void sendData( Communication c )
   {
      try // send object to client
      {
         output.writeObject( c );
         output.flush(); // flush output to client
         displayMessage( "\n SERVER>>> " + c.location );
      } // end try
      catch ( IOException ioException ) 
      {
          ioException.printStackTrace();
         //displayArea.append( "\nError writing object" );
      } // end catch
   } // end method sendData

   // manipulates displayArea in the event-dispatch thread
   private void displayMessage( final String messageToDisplay )
   {
       System.out.println(messageToDisplay);
   } // end method displayMessage

   // manipulates enterField in the event-dispatch thread
//   private void setTextFieldEditable( final boolean editable )
//   {
//      SwingUtilities.invokeLater(
//         new Runnable()
//         {
//            public void run() // sets enterField's editability
//            {
//               enterField.setEditable( editable );
//            } // end method run
//         }  // end inner class
//      ); // end call to SwingUtilities.invokeLater
//   } // end method setTextFieldEditable
} // end class Server

/**************************************************************************
 * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and               *
 * Pearson Education, Inc. All Rights Reserved.                           *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/